import { BaseService } from '@/core/base.service';
import { SKUListDto, SKUQueryDto } from '@/dtos';
import { Injectable } from '@nestjs/common';
import { Prisma, SKU } from '@prisma/client';

@Injectable()
export class SKUService extends BaseService {
  async list({ params, sort }: SKUListDto) {
    const { current = 1, pageSize = 20, keyword, ...where } = params;

    let sql = `
            SELECT #{fields} FROM \`SKU\` AS t
            WHERE t.isDeleted = false
              AND t.isEnabled = true
            ${where.spuId ? `AND t.spuId = ${where.spuId}` : ''}
        `;

    const [{ count }] = await this.prisma.$queryRawUnsafe<[{ count: number }]>(
      sql.replace('#{fields}', 'COUNT(t.id) AS count'),
    );

    const list = await this.prisma.$queryRawUnsafe<SKU[]>(
      `${sql.replace(
        '#{fields}',
        `
          t.id, t.title, t.image, t.stock, t.price, t.sort
        `,
      )}
            ORDER BY ${
              !!sort && Object.keys(sort).length > 0
                ? Object.entries(sort)
                    .map(
                      ([k, v]) => `t.${k} ${v === 'descend' ? 'DESC' : 'ASC'}`,
                    )
                    .join(',')
                : 't.sort DESC'
            }
            LIMIT ${pageSize} 
            OFFSET ${(current - 1) * pageSize}
        `,
    );

    const total = count ? Number(count) : 0;
    const totalPage = Math.ceil(total / pageSize);
    const hasMore = current < totalPage;

    return {
      total,
      totalPage,
      hasMore,
      current,
      pageSize,
      list: list.map((o) => ({
        ...o,
        price: Number(o.price),
      })),
    };
  }

  async query({ params, sort }: SKUQueryDto) {
    const { current = 1, pageSize = 20, keyword, ...where } = params;

    let sql = `
            SELECT #{fields} FROM \`SKU\` AS t
            WHERE t.isDeleted = false
            ${where.spuId ? `AND t.spuId = ${where.spuId}` : ''}
        `;

    const [{ count }] = await this.prisma.$queryRawUnsafe<[{ count: number }]>(
      sql.replace('#{fields}', 'COUNT(t.id) AS count'),
    );

    const list = await this.prisma.$queryRawUnsafe<SKU[]>(
      `${sql.replace(
        '#{fields}',
        `
            t.id, t.title, t.image, t.stock, t.price, t.sort,
            t.isEnabled, t.createdAt
        `,
      )}
            ORDER BY ${
              !!sort && Object.keys(sort).length > 0
                ? Object.entries(sort)
                    .map(
                      ([k, v]) => `t.${k} ${v === 'descend' ? 'DESC' : 'ASC'}`,
                    )
                    .join(',')
                : 't.createdAt DESC'
            }
            LIMIT ${pageSize} 
            OFFSET ${(current - 1) * pageSize}
        `,
    );

    const total = count ? Number(count) : 0;
    const totalPage = Math.ceil(total / pageSize);
    const hasMore = current < totalPage;

    return {
      total,
      totalPage,
      hasMore,
      current,
      pageSize,
      list: list.map((o) => ({
        ...o,
        price: Number(o.price),
      })),
    };
  }

  async findOne(
    where: Prisma.SKUWhereUniqueInput,
    select?: Prisma.SKUSelect,
  ): Promise<SKU | null> {
    return this.prisma.sKU.findUnique({
      where,
      select,
    });
  }

  async create(data: Prisma.SKUCreateInput): Promise<SKU> {
    return await this.prisma.sKU.create({
      data: {
        ...data,
      },
    });
  }

  async update(params: {
    where: Prisma.SKUWhereUniqueInput;
    data: Prisma.SKUUpdateInput;
  }): Promise<SKU> {
    const { where, data } = params;
    return this.prisma.sKU.update({
      where,
      data: {
        ...data,
      },
    });
  }
}
